import * as API from '../api/request_api.js'

Page({
  data: {
    roomID:null, 
    roomName:null,
    roomDevice:null,
    ctrlLightSwitch: "开",
    type_switch: "开",
    tcpclient : 0
  },
  /**
   * 生命周期函数--监听页面加载
   */ 
  onLoad: function (options) {
    var that = this
    that.setData({
      deviceID: options.deviceID,
      deviceName: options.deviceName,
      deviceOnline: options.deviceOnline
    })
  },

  button_connect_device(){ //确认信息
    let that = this
    console.log("测试TCP连接");
    wx.showLoading({
      title: '连接中...',
    })
    const tcp = wx.createTCPSocket()
    that.tcpclient = tcp
    tcp.connect({
      address: '192.168.4.1',
      port: 6666
    })
    tcp.onConnect(() => {
      wx.hideLoading();
      API.ShowToast("tcp已连接", 1500, "error")
      tcp.write("USER")
    })
    tcp.onMessage((message) => {
      console.log(message.message)
      wx.hideLoading();
      let msgView = new DataView(message.message);
      if(msgView.getUint8(0) == 49 & msgView.getUint8(1) == 50){
        tcp.close()
        console.log("成功！！！")
        that.setData({
          sty:2
        })
        //return true
      }else{
        console.log("成功！！！")
        API.ShowToast("失败！", 2000, "error")
        //return false
      }
    })
    tcp.onError((res) => {
      wx.hideLoading();
      API.ShowToast("tcp.onError", 2000, "error")
      console.log(res)
      return false
    })
  },

  button_GO(){
    let that = this
    console.log("G")
    that.tcpclient.write("G")
  },

  button_BACK(){
    let that = this
    console.log("B")
    that.tcpclient.write("B")
  },

  button_PASS(){
    let that = this
    console.log("P")
    that.tcpclient.write("P")
    setTimeout(function () {
      that.tcpclient.write("P")
    },150) //delayTime是延迟时间，以毫秒为单位，1000ms=1s
  },

  button_STOP(){
    let that = this
    console.log("S")
    that.tcpclient.write("S")
  },

  button_TURN_LEFT(){
    let that = this
    console.log("L")
    that.tcpclient.write("L")
  },

  button_TURN_RIGHT(){
    let that = this
    console.log("R")
    that.tcpclient.write("R")
  },

  button_TURN_NONE(){
    let that = this
    console.log("M") //中间midiom
    that.tcpclient.write("M")
    setTimeout(function () {
      that.tcpclient.write("M")
    },150) //delayTime是延迟时间，以毫秒为单位，1000ms=1s
  },

  //滑动条滑动过程中触发的事件
  slider_1: function (e) {
    let that = this
    console.log(e.detail.value)
    that.tcpclient.write("Q"+e.detail.value.toString())
  },

  //滑动条滑动过程中触发的事件
  slider_2: function (e) {
    let that = this
    console.log(e.detail.value)
    that.tcpclient.write("E"+e.detail.value.toString())
  },

});
